package com.knight.concurrent.chapter8;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Optional;

/**
 * 控制同时只能有固定线程数执行
 *
 * @author: knight
 * @Date: 2019-03-06 20:45
 */
public class CaptureService {

    private final static LinkedList<Control> CONTROLS = new LinkedList<>();

    private static final int MAX_THREAD_NUM = 5;

    public static void main(String[] args) {
        ArrayList<Thread> worker = new ArrayList<>();
        Arrays.asList("M1", "M2", "M3", "M4", "M5", "M6", "M7", "M8", "M9", "M10").stream().map(CaptureService::createCaptureThread).forEach(thread -> {
            thread.start();
            worker.add(thread);
        });

        worker.forEach(t -> {
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        Optional.of("所有线程全部工作完成").ifPresent(System.out::println);
    }


    public static Thread createCaptureThread(String name) {


        return new Thread(() -> {
            Optional.of("线程[" + name + "]准备执行").ifPresent(System.out::println);
            synchronized (CONTROLS) {
                while (CONTROLS.size() >= MAX_THREAD_NUM) {
                    try {
                        CONTROLS.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                CONTROLS.addLast(new Control());
            }
            Optional.of("线程[" + name + "]正在运行").ifPresent(System.out::println);
            try {
                Thread.sleep(20_000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            synchronized (CONTROLS) {
                CONTROLS.removeFirst();
                CONTROLS.notifyAll();
                Optional.of("线程[" + name + "]运行结束").ifPresent(System.out::println);
            }
        }, name);
    }

    public static class Control {

    }


}
